package post

import (
	"context"
	// "fmt"
	"strconv"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetPostByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPostByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostByIdLogic {
	return &GetPostByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPostByIdLogic) GetPostById(
	req *types.PostIdReq,
	headers *[]*types.Header,
) (resp *types.KbEntryInfo, err error) {
	if req.Id == nil || *req.Id == 0 {
		return &types.KbEntryInfo{}, nil
	}

	userId := jwt.GetUserId(l.ctx)

	preload := "blogPost:Id,ParentId,Title,Slug,Excerpt,Date"
	eagerLoad := "blogPost:blogPostDetail,blogPostMeta,blogMedia,blogTerm"
	preload += ";blogPostDetail:ContentHtml"
	preload += ";blogPostMeta:mediaId,mediaUrl,viewCount,commentCount,forwardCount"
	preload += ";blogMedia:Id,Url,Thumbnail,Order,altText,metaData"
	preload += ";blogTerm:Id,Name,Slug"
	var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini

	var searchLogId *uint64
	if req.SearchId != nil && *req.SearchId > 0 {
		searchLogId = pointy.GetPointer(uint64(*req.SearchId))
	} else {
		searchLogId = pointy.GetPointer(uint64(0))
	}

	res, err := l.svcCtx.BlogRpc.GetPostById(l.ctx, &blogclient.BaseIdReq{
		Id:          req.Id,
		Preload:     pointy.GetPointer(preload),
		EagerLoad:   pointy.GetPointer(eagerLoad),
		VisitorId:   pointy.GetPointer(userId),
		PlatformId:  pointy.GetPointer(platformId),
		SearchLogId: searchLogId,
	})
	if err != nil {
		logx.Errorw("GetPostById err", logx.Field("detail", err.Error()))
		return &types.KbEntryInfo{}, nil
	}

	if res == nil || res.Id == nil || *res.Id == 0 {
		return &types.KbEntryInfo{}, nil
	}

	var viewCount *uint32
	var commentCount *uint32
	var forwardCount *uint32
	var imageUrl *string
	if len(res.Meta) > 0 {
		for _, v := range res.Meta {
			if v.Key == nil || v.Value == nil {
				continue
			}

			val := *v.Value
			switch *v.Key {
			case "viewCount":
				if i, err := strconv.ParseInt(val, 10, 32); err == nil {
					viewCount = pointy.GetPointer(uint32(i))
				}
			case "commentCount":
				if i, err := strconv.ParseInt(val, 10, 32); err == nil {
					commentCount = pointy.GetPointer(uint32(i))
				}
			case "forwardCount":
				if i, err := strconv.ParseInt(val, 10, 32); err == nil {
					forwardCount = pointy.GetPointer(uint32(i))
				}
			case "mediaUrl":
				imageUrl = pointy.GetPointer(val)
			}
		}
	}

	var media []*types.TmpMediaInfo
	if len(res.Media) > 0 {
		for _, v := range res.Media {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}

			media = append(media, &types.TmpMediaInfo{
				Uid:       v.Uid,
				Id:        v.Id,
				Thumbnail: v.Thumbnail,
				Order:     v.Order,
				Url:       pointy.GetPointer(url),
				AltText:   v.AltText,
			})
		}
	}

	var categories []*types.TermInfo
	if len(res.Categories) > 0 {
		for _, v := range res.Categories {
			categories = append(categories, &types.TermInfo{
				Id:   v.Id,
				Name: v.Name,
				Slug: v.Slug,
			})
		}
	}

	var tags []*types.TermInfo
	if len(res.Tags) > 0 {
		for _, v := range res.Tags {
			tags = append(tags, &types.TermInfo{
				Id:   v.Id,
				Name: v.Name,
				Slug: v.Slug,
			})
		}
	}

	//err = l.createFeedBack(globalkey.GorseBLogPostPrefix+strconv.FormatUint(*req.Id, 10), strconv.FormatUint(userId, 10))
	//if err != nil {
	//	logx.Errorf("GetPostById-blogPost createFeedBack Error: %v", err)
	//}

	return &types.KbEntryInfo{
		Id:            res.Id,
		Title:         res.Title,
		Slug:          res.Slug,
		Content:       res.Content,
		Excerpt:       res.Excerpt,
		CommentStatus: res.CommentStatus,
		ParentId:      res.ParentId,
		PublicDate:    res.PublicDate,
		CreatedAt:     res.CreatedAt,
		UpdatedAt:     res.UpdatedAt,
		ImageUrl:      imageUrl,
		ViewCount:     viewCount,
		CommentCount:  commentCount,
		ForwardCount:  forwardCount,
		Media:         media,
		Categories:    categories,
		Tags:          tags,
	}, nil
}

func (l *GetPostByIdLogic) createFeedBack(pid, uid string) error {
	return l.svcCtx.GorseClient.CreateFeedback(
		l.svcCtx.Config.Query.GorseUrl,
		pid, uid,
		globalkey.RecommendedFeedBackTypeRead,
	)
}
